package com.yidi.system.service.imp;

import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.AjaxResult;
import com.yidi.common.core.domain.entity.SysDictData;
import com.yidi.common.core.domain.entity.SysDictType;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.utils.DictUtils;
import com.yidi.common.utils.StringUtils;
import com.yidi.system.repository.SysDictDataRepository;
import com.yidi.system.repository.SysDictTypeRepository;
import com.yidi.system.service.SysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：Xn
 * @ClassName: SysDictTypeServiceImpl
 * @date ：2021-10-19 14:37
 * @describe ：
 */
@Service
public class SysDictTypeServiceImpl extends AbstractBaseService<SysDictType> implements SysDictTypeService{

    @Autowired
    private SysDictDataRepository dictDataRepository;

    @Autowired
    private SysDictTypeRepository sysDictTypeRepository;

    /**
     * 分页
     */
    @Override
    public Page<SysDictType> findByPage(Integer pageNo, Integer pageSize, SysDictType dictType) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC, "id"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Page<SysDictType> page = sysDictTypeRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(dictType.getDictName())) {
                list.add(cb.and(cb.like(root.get("dictName").as(String.class), dictType.getDictName())));
            }

            if(StringUtils.isNotBlank(dictType.getStatus())) {
                list.add(cb.and(cb.equal(root.get("status").as(String.class), dictType.getStatus())));
            }

            if(StringUtils.isNotBlank(dictType.getDictTypes())) {
                list.add(cb.and(cb.like(root.get("dictTypes").as(String.class), dictType.getDictTypes())));
            }

            Map<String, Object> params = dictType.getParams();
            if(params != null) {
                String beginTime = (String) params.get("beginTime");
                String endTime = (String) params.get("endTime");
                if(StringUtils.isNotBlank(beginTime)) {
                    try {
                        list.add(cb.and(cb.greaterThanOrEqualTo(root.get("createTime"), sdf.parse(beginTime))));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(StringUtils.isNotBlank(endTime)) {
                    try {
                        list.add(cb.and(cb.lessThanOrEqualTo(root.get("createTime"), sdf.parse(endTime))));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },pageable);

        return page;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict)
    {
        Long dictId = StringUtils.isNull(dict.getId()) ? -1L : dict.getId();
        SysDictType dictType = sysDictTypeRepository.findByDictTypes(dict.getDictTypes());

        if (StringUtils.isNotNull(dictType) && !dictType.getId().equals(dictId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public void insertDictType(SysDictType dict)
    {
        add(dict);

        DictUtils.setDictCache(dict.getDictTypes(), null);
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateDictType(SysDictType dictType)
    {
        SysDictType oldType = findById(dictType.getId());
        List<SysDictData> oldData = dictDataRepository.findByDictTypes(oldType.getDictTypes());
        if(oldData.size() > 0) {
            dictDataRepository.updateDictDataType(dictType.getDictTypes(), oldType.getDictTypes());
        }
        oldType.setDictName(dictType.getDictName());
        oldType.setDictTypes(dictType.getDictTypes());
        oldType.setStatus(dictType.getStatus());
        oldType.setRemark(dictType.getRemark());
        modify(oldType);

        List<SysDictData> dictDatas = dictDataRepository.selectDictDataByType(dictType.getDictTypes());
        DictUtils.setDictCache(dictType.getDictTypes(), dictDatas);
    }

    /**
     * 批量删除字典类型
     *
     * @param ids 需要删除的数据
     * @return 结果
     */
    @Override
    public AjaxResult deleteDictTypeByIds(Long[] ids)
    {
        for (Long dictId : ids)
        {
            SysDictType dictType = findById(dictId);
            if (dictDataRepository.countDictDataByType(dictType.getDictTypes()) > 0)
            {
                return AjaxResult.error( "已分配,不能删除");
            }
        }

        for(Long id : ids) {
            SysDictType dict = findById(id);
            delete(id);
            DictUtils.removeDictCache(dict.getDictTypes());
        }


        return AjaxResult.success();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = dictDataRepository.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        List<SysDictType> dictTypeList = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for (SysDictType dict : dictTypeList)
        {
            List<SysDictData> dictDatas = dictDataRepository.selectDictDataByType(dict.getDictTypes());
            DictUtils.setDictCache(dict.getDictTypes(), dictDatas);
        }
    }
}
